package com.ty.cloudpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.cloudpicture.annotation.AuthCheck;
import com.ty.cloudpicture.common.*;
import com.ty.cloudpicture.exception.BusinessException;
import com.ty.cloudpicture.exception.ThrowUtils;
import com.ty.cloudpicture.model.dto.user.*;
import com.ty.cloudpicture.model.entity.User;
import com.ty.cloudpicture.model.vo.UserVO;
import com.ty.cloudpicture.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
@RequiredArgsConstructor
@Api(tags = "用户接口")
public class UserController {
    private final UserService userService;

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> userRegister (@RequestBody UserRegisterDTO userRegisterDTO){
        ThrowUtils.throwIf(userRegisterDTO == null, ErrorCode.PARAMS_ERROR);
        log.info("用户注册");
        String userAccount = userRegisterDTO.getUserAccount();
        String userPassword = userRegisterDTO.getUserPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        long result =userService.register(userAccount,userPassword,checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     * @param userLoginDTO
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<User> userLogin (@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request){
        ThrowUtils.throwIf(userLoginDTO == null, ErrorCode.PARAMS_ERROR);
        log.info("用户登录");
        String userAccount = userLoginDTO.getUserAccount();
        String userPassword = userLoginDTO.getUserPassword();
        User result =userService.login(userAccount,userPassword,request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation(value = "获取当前登录用户信息")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request){
        User user = userService.getLoginUser(request);
        return ResultUtils.success(userService.getUserVO(user));
    }
    @PostMapping("/logout")
    @ApiOperation(value = "用户注销")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request){
        ThrowUtils.throwIf(request==null,ErrorCode.PARAMS_ERROR,"未登录");
        Boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }
    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody AddUserDTO addUserDTO){
        ThrowUtils.throwIf(addUserDTO==null,ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(addUserDTO,user);
        //设置默认密码
        final String defaultPassword = "12345678";
        String encryptPassword = userService.encryptPassword(defaultPassword);
        user.setUserPassword(encryptPassword);
        boolean save = userService.addUser(user);
        ThrowUtils.throwIf(!save,ErrorCode.PARAMS_ERROR,"添加失败");
        return ResultUtils.success(user.getId(),"添加成功");
    }
    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteUserRequest deleteUserRequest){
        Long id = deleteUserRequest.getId();
        if (id==null || id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数异常");
        }
        boolean removeById = userService.removeById(id);
        ThrowUtils.throwIf(!removeById,ErrorCode.PARAMS_ERROR,"删除失败");
        return ResultUtils.success(removeById);
    }
    @PostMapping("/update")
    @ApiOperation(value = "更新用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UpdateUserDTO updateUserDTO){
        ThrowUtils.throwIf(updateUserDTO==null,ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(updateUserDTO,user);
        boolean update = userService.updateById(user);
        ThrowUtils.throwIf(!update,ErrorCode.PARAMS_ERROR,"更新失败");
        return ResultUtils.success(true);
    }

    @PostMapping("/list/page/vo")
    @ApiOperation(value = "分页获取用户列表")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> ListUserVOByPage(@RequestBody UserQueryRequest userQueryRequest){
        ThrowUtils.throwIf(userQueryRequest==null,ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }
    @GetMapping("/get")
    @ApiOperation(value = "根据id获取用户")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserVO> getUserById(@RequestParam Long id){
        ThrowUtils.throwIf(id==null || id<=0,ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user==null,ErrorCode.PARAMS_ERROR,"用户不存在");
        return ResultUtils.success(userService.getUserVO(user));
    }
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据id获取用户VO")
    public BaseResponse<UserVO> getUserVOById(@RequestParam Long id){
        ThrowUtils.throwIf(id==null || id<=0,ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user==null,ErrorCode.PARAMS_ERROR,"用户不存在");
        return ResultUtils.success(userService.getUserVO(user));
    }
    @PostMapping("/update/my")
    @ApiOperation(value = "更新当前用户信息")
    public BaseResponse<UserVO> updateUserInfo(@RequestBody User updateUser, HttpServletRequest request) {
        // 1. 校验参数
        if (updateUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 2. 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        
        // 3. 更新用户信息
        boolean result = userService.updateUserInfo(loginUser, updateUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        
        // 4. 获取更新后的用户信息
        User updatedUser = userService.getById(loginUser.getId());
        
        // 5. 返回脱敏后的用户信息
        return ResultUtils.success(userService.getUserVO(updatedUser));
    }
    //TODO 用户修改自己的密码、忘记密码
}
